<template>
  <view class="containerDoc">
    <view class="page-container" :style="listHeightStylePage">
      <!-- 导航栏 -->
      <u-navbar :title="buttonTip" placeholder @leftClick="back" :border="false" :shadow="true"></u-navbar>
      <view style="padding: 20rpx;" :style="listHeightStyle">
        <web-view id="Faceregistration" ref="Faceregistrationwebview" :src="FaceRul"
          @message="handleMessage"></web-view>
      </view>
    </view>



    <up-modal :show="show" :title="title" :content='content' @confirm="Faceconfirm">
      <view class="slot-content">
        <rich-text :nodes="content"></rich-text>
      </view>
    </up-modal>


    <!-- 消息提示	 -->
    <u-toast ref="uToast" />
  </view>
</template>
<script>
import clock from "@/apis/cloud/clock";
import { useClockStore, useUserStore } from "@/pinia-store/user";
import { mapStores } from "pinia";
export default {
  data () {
    return {
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      appHeight: null,
      topHeight: 0,
      listHeightStylePage: {},
      scrollViewHeight: {}, // 动态计算 scroll-view 的高度
      FaceRul: '/hybrid/html/modifyFaceregistration.html',
      show: false,
      title: '',
      content: '',
      isfirstrlsbstatus: 0,
      buttonTip: '',
      Facemanagement: true, // 是否修改人脸
    }
  },
  computed: {
    ...mapStores(useUserStore, useClockStore)
  },
  onLoad (value) {
    this.Facemanagement = value?.Facemanagement == 'false' ? false : true
    this.isfirstrlsbstatus = value.isfirstrlsbstatus || 1
    if (!this.Facemanagement) {
      this.titleTips = '请把人脸放在圆圈内拍摄脸部，开始人脸识别'
      this.buttonTip = '人脸上传'
      return
    }

    if (value.isfirstrlsbstatus == 1) {
      this.buttonTip = '人脸上传'
    } else {
      this.show = true
      this.buttonTip = '上传人脸注册'
      this.title = '上传人脸提示'
      this.content = '您尚未注册人脸信息，请上传清晰的人脸照片，用于后续打卡认证。'
    }
    this.isfirstrlsbstatus = value?.isfirstrlsbstatus
  },
  async mounted () {
    window.addEventListener("message", this.handleMessage);
  },
  onUnload () {
    // 移除事件监听
    window.removeEventListener('message', this.handleMessage);
  },
  async created () {
    this.appHeight = uni.getSystemInfoSync();
    this.topHeight = this.appHeight.screenHeight;
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif
    // #ifdef APP-PLUS
    this.listHeightStylePage = {
      height: `${this.topHeight}px`,
    };
    // #endif
    await this.calculateListHeight();
  },
  methods: {
    // 处理从 local.html 接收的经纬度
    async handleMessage (event) {
      if (event.data && event.data.type === 'ModifygetFaceregistration') {
        try {
          this.handleSetTime(event.data.params)
        } catch (error) {
          console.error('Failed to parse position:', error);
        }
      }
    },
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const navbarHeight = 52; // 导航栏高度（假设为 44px）
      const tabsHeight = 88;
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        height: `${this.topHeight - 164}px`,
        overflowY: 'auto'
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'auto'
      };
      // #endif
    },

    Faceconfirm () {
      if (this.content == '上传人脸成功' || this.content == '修改人脸成功') {
        this.show = false
        this.isfirstrlsbstatus = 1
        uni.navigateBack();
      } else {
        this.show = false
      }
    },
    resertAll () {
      this.buttonTip = "上传人脸"
      this.snapshotInfo = '' // 快照信息
      this.showCountDown = false // 拍摄倒计时
      this.timeOut = this.snapCountdownTimer
      this.isPass = null // 是否通过人脸认证
    },
    startPreview () {
      const _that = this
      _that.handleSetTime()
    },

    handleSetTime (filePath) {
      // 人脸上传
      if (this.isfirstrlsbstatus == 1) {
        try {
          this.$refs.uToast.show({
            icon: false,
            message: '上传人脸中...',
            duration: -1
          })
          // 更换人脸接口
          uni.uploadFile({
            url: 'https://cloud.mfarmers.com/dist/interface/public/index.php/index/Kaoqin/ResetHeaderImg',
            filePath: filePath,
            formData: {
              'phone': this.userStore.user.phone,
              'worker_id': this.userStore.user.worker_id,
            },
            name: "file",
            success: (res) => {
              let resData = JSON.parse(res.data)
              if (resData.status == 1 && resData.flag == 1) {
                this.$refs.uToast.hide()
                this.show = true
                this.content = '修改人脸成功'
              } else {
                this.$refs.uToast.hide()
                uni.$u.toast('未检测到人脸，请保持正脸在取景框中');
              }
            },
            fail: (err) => {
              uni.$u.toast('更换人脸失败');
            },
          })

        } catch (error) {
          this.$refs.uToast.hide()
          uni.$u.toast('更换人脸失败');
        }

        return
      }

      // 人脸注册
      this.$refs.uToast.show({
        icon: false,
        message: '上传人脸中...',
        duration: -1
      })
      // 注册人脸接口
      uni.uploadFile({
        url: 'https://cloud.mfarmers.com/dist/interface/public/index.php/index/Kaoqin/rlsb_upload',
        filePath: filePath,
        formData: {
          'phone': this.userStore.user.phone,
          'worker_id': this.userStore.user.worker_id,
        },
        name: "file",
        success: (uploadFileRes) => {
          const upData = JSON.parse(uploadFileRes.data)
          if (upData.status == 1 && upData.flag == 1) {
            if (this.isfirstrlsbstatus == 0) {
              this.$refs.uToast.hide()
              this.show = true
              this.content = '上传人脸成功'
            }
          } else {
            this.$refs.uToast.hide()
            uni.$u.toast('未检测到人脸，请保持正脸在取景框中');
          }
        },
        fail: (error) => {
        },
        complete: () => {
        }
      });

    },

    back () {
      uni.navigateBack();
    }

  },
}
</script>

<style scoped lang="scss">
.containerDoc {
  overflow: hidden;
  background-color: #f3f4f5;

  .page-container {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}
</style>
